/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hibernate.dao;

import hibernate.entity.Course;
import hibernate.entity.Student;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import util.HibernateUtil;

/**
 *
 * @author NDH
 */
public class StudentDAO extends AbstractDAO {

    public List<Student> readAll() {
        session = HibernateUtil.getSessionFactory().openSession();
        query = session.createQuery("from Student");
        return query.list();
    }

    public List<Student> readByCourse(int id) {
        session = HibernateUtil.getSessionFactory().openSession();
        query = session.createQuery("from Student s inner join s.Coursetudent as cs where cs.courseId =:id ");
        query.setParameter("id", id);
        return query.list();
    }

    public List<Student> readByCourse(Course c) {
        Iterator<Student> allStu = c.getStudents().iterator();
        ArrayList<Student> listS = new ArrayList<>();
        while (allStu.hasNext()) {
            Student student = allStu.next();
            listS.add(student);
        }
        return listS;
    }

    public Student readByID(int id) {
        session = HibernateUtil.getSessionFactory().openSession();
        query = session.createQuery("from Student where loginId =:id");
        query.setParameter("id", id);
        return (Student) query.list().get(0);
    }

    public int create(Student s) {
        session = HibernateUtil.getSessionFactory().openSession();
        try {
            tx = session.beginTransaction();
            session.save(s);
            tx.commit();
            return 1;
        } catch (Exception e) {
            tx.rollback();
            return 0;
        }
    }

    public int delete(Student s) {
        session = HibernateUtil.getSessionFactory().openSession();
        try {
            tx = session.beginTransaction();
            session.delete(s);
            tx.commit();
            return 1;
        } catch (Exception e) {
            tx.rollback();
            return 0;
        }
    }

    public int update(Student s) {
        session = HibernateUtil.getSessionFactory().openSession();
        try {
            tx = session.beginTransaction();
            session.saveOrUpdate(s);
            tx.commit();
            return 1;
        } catch (Exception e) {
            tx.rollback();
            return 0;
        }
    }

    public static void main(String[] args) {

        new StudentDAO().readAll();
    }
}
